<template>
  <view class="chat-container">
    <!-- 头部 -->
    <view class="chat-header">
      <text class="chat-title">智能客服</text>
      <text class="online-status">在线</text>
    </view>
    
    <!-- 聊天消息区域 -->
    <scroll-view 
      class="chat-messages" 
      scroll-y="true" 
      :scroll-top="scrollTop"
      :scroll-with-animation="true"
      @scrolltoupper="loadMoreMessages"
      upper-threshold="50"
      ref="messagesScroll"
    >
      <!-- 欢迎消息 -->
      <view class="message-date-divider">
        <text>{{ formatDate(new Date()) }}</text>
      </view>
      
      <!-- 系统欢迎消息 -->
      <view class="message-item service">
        <image class="avatar" src="/static/robot-avatar.png" mode="aspectFill"></image>
        <view class="message-content">
          <text class="message-text">您好，我是智能客服助手，有什么可以帮助您的吗？</text>
        </view>
      </view>
      
      <!-- 消息列表 -->
      <block v-for="(msg, index) in messages" :key="index">
        <!-- 用户消息 -->
        <view v-if="msg.type === 'user'" class="message-item user">
          <view class="message-content">
            <text class="message-text">{{ msg.content }}</text>
          </view>
          <image class="avatar" :src="userAvatar" mode="aspectFill"></image>
        </view>
        
        <!-- 服务消息 -->
        <view v-else class="message-item service">
          <image class="avatar" src="/static/robot-avatar.png" mode="aspectFill"></image>
          <view class="message-content">
            <text class="message-text">{{ msg.content }}</text>
          </view>
        </view>
      </block>
      
      <!-- 正在输入指示器 -->
      <view v-if="isTyping" class="message-item service">
        <image class="avatar" src="/static/robot-avatar.png" mode="aspectFill"></image>
        <view class="message-content typing">
          <view class="typing-indicator">
            <view class="dot"></view>
            <view class="dot"></view>
            <view class="dot"></view>
          </view>
        </view>
      </view>
    </scroll-view>
    
    <!-- 输入区域 -->
    <view class="chat-input-area">
      <view class="quick-questions" v-if="showQuickQuestions">
        <view 
          class="quick-question-item" 
          v-for="(question, idx) in quickQuestions" 
          :key="idx"
          @tap="selectQuickQuestion(question)"
        >
          {{ question }}
        </view>
      </view>
      
      <view class="input-container">
        <input 
          class="message-input" 
          type="text" 
          v-model="inputMessage" 
          placeholder="请输入您的问题..." 
          confirm-type="send"
          @confirm="sendMessage"
          @focus="showQuickQuestions = false"
        />
        <view class="quick-questions-btn" @tap="toggleQuickQuestions">
          <text class="iconfont">?</text>
        </view>
        <view class="send-btn" @tap="sendMessage" :class="{ 'active': inputMessage.trim() }">
          <text>发送</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { chatApi } from '@/api/chat.js'

export default {
  data() {
    return {
      inputMessage: '',
      messages: [],
      isTyping: false,
      scrollTop: 0,
      showQuickQuestions: true,
      quickQuestions: [
        '如何预约课程？',
        '如何查看我的订单？',
        '会员有什么特权？',
        '如何申请退款？'
      ],
      userAvatar: '/static/default-avatar.png'
    }
  },
  
  onLoad() {
    // 尝试获取用户头像
    try {
      const userInfo = uni.getStorageSync('userInfo')
      if (userInfo && userInfo.avatarUrl) {
        this.userAvatar = userInfo.avatarUrl
      }
    } catch (e) {
      console.error('获取用户信息失败', e)
    }
  },
  
  methods: {
    // 发送消息
    sendMessage() {
      const message = this.inputMessage.trim()
      if (!message) return
      
      // 添加用户消息
      this.messages.push({
        type: 'user',
        content: message,
        time: new Date()
      })
      
      this.inputMessage = ''
      this.scrollToBottom()
      
      // 显示AI正在输入状态
      this.isTyping = true
      
      // 使用API封装获取AI回复
      chatApi.getAIResponse(message)
        .then(res => {
          this.isTyping = false
          if (res.code === 200) {
            // 添加AI回复消息
            this.messages.push({
              type: 'service',
              content: res.data.content,
              time: new Date()
            })
            this.scrollToBottom()
          } else {
            uni.showToast({
              title: '获取回复失败',
              icon: 'none'
            })
          }
        })
        .catch(err => {
          console.error('获取AI回复失败:', err)
          this.isTyping = false
          uni.showToast({
            title: '获取回复失败，请重试',
            icon: 'none'
          })
        })
    },
    
    // 滚动到底部
    scrollToBottom() {
      setTimeout(() => {
        let query = uni.createSelectorQuery().in(this)
        query.select('.chat-messages').boundingClientRect()
        query.select('.chat-messages').scrollOffset()
        query.exec(res => {
          if (res && res[0] && res[1]) {
            this.scrollTop = res[1].scrollHeight
          }
        })
      }, 100)
    },
    
    // 加载更多历史消息（示例，实际应实现分页）
    loadMoreMessages() {
      // 实际项目中，应该从服务器加载更早的聊天记录
      console.log('加载更多历史消息')
    },
    
    // 选择快速问题
    selectQuickQuestion(question) {
      this.inputMessage = question
      this.sendMessage()
      this.showQuickQuestions = false
    },
    
    // 切换快速问题显示
    toggleQuickQuestions() {
      this.showQuickQuestions = !this.showQuickQuestions
    },
    
    // 格式化日期
    formatDate(date) {
      const today = new Date()
      const messageDate = new Date(date)
      
      if (
        today.getFullYear() === messageDate.getFullYear() &&
        today.getMonth() === messageDate.getMonth() &&
        today.getDate() === messageDate.getDate()
      ) {
        return '今天'
      }
      
      return `${messageDate.getFullYear()}年${messageDate.getMonth() + 1}月${messageDate.getDate()}日`
    }
  }
}
</script>

<style>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f8f8f8;
}

.chat-header {
  padding: 24rpx 30rpx;
  background-color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  border-bottom: 1rpx solid #eee;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.chat-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.online-status {
  position: absolute;
  right: 30rpx;
  font-size: 24rpx;
  color: #4caf50;
  padding: 4rpx 16rpx;
  background-color: rgba(76, 175, 80, 0.1);
  border-radius: 20rpx;
}

.chat-messages {
  flex: 1;
  padding: 20rpx 30rpx;
  position: relative;
  overflow-y: auto;
}

.message-date-divider {
  text-align: center;
  margin: 30rpx 0;
}

.message-date-divider text {
  font-size: 24rpx;
  color: #999;
  background-color: rgba(255, 255, 255, 0.8);
  padding: 6rpx 20rpx;
  border-radius: 20rpx;
  box-shadow: 0 2rpx 5rpx rgba(0, 0, 0, 0.05);
}

.message-item {
  display: flex;
  margin-bottom: 40rpx;
  position: relative;
  transition: all 0.3s ease;
}

.message-item.user {
  flex-direction: row-reverse;
}

.avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background-color: #e0e0e0;
  margin: 0 20rpx;
  border: 2rpx solid #fff;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.message-content {
  max-width: 70%;
  border-radius: 18rpx;
  padding: 20rpx 24rpx;
  word-break: break-word;
  position: relative;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  line-height: 1.5;
}

.message-item.service .message-content {
  background-color: #ffffff;
  border: 1rpx solid #e8e8e8;
  border-top-left-radius: 4rpx;
}

.message-item.service .message-content:before {
  content: '';
  position: absolute;
  left: -10rpx;
  top: 20rpx;
  width: 0;
  height: 0;
  border-top: 10rpx solid transparent;
  border-right: 14rpx solid #ffffff;
  border-bottom: 10rpx solid transparent;
}

.message-item.user .message-content {
  background-color: #4080FF;
  border-top-right-radius: 4rpx;
}

.message-item.user .message-content:before {
  content: '';
  position: absolute;
  right: -10rpx;
  top: 20rpx;
  width: 0;
  height: 0;
  border-top: 10rpx solid transparent;
  border-left: 14rpx solid #4080FF;
  border-bottom: 10rpx solid transparent;
}

.message-text {
  font-size: 30rpx;
  line-height: 1.6;
}

.message-item.service .message-text {
  color: #333;
}

.message-item.user .message-text {
  color: #fff;
}

.typing-indicator {
  display: flex;
  align-items: center;
  padding: 10rpx;
}

.dot {
  width: 12rpx;
  height: 12rpx;
  border-radius: 50%;
  background-color: #999;
  margin: 0 5rpx;
  animation: typing 1.5s infinite ease-in-out;
}

.dot:nth-child(1) {
  animation-delay: 0s;
}

.dot:nth-child(2) {
  animation-delay: 0.2s;
}

.dot:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
    opacity: 0.6;
  }
  30% {
    transform: translateY(-10rpx);
    opacity: 1;
  }
}

.chat-input-area {
  padding: 20rpx;
  background-color: #fff;
  border-top: 1rpx solid #eee;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.quick-questions {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 20rpx;
  transition: all 0.3s ease;
}

.quick-question-item {
  background-color: #f5f5f5;
  padding: 12rpx 24rpx;
  border-radius: 30rpx;
  margin: 10rpx;
  font-size: 26rpx;
  color: #333;
  box-shadow: 0 2rpx 5rpx rgba(0, 0, 0, 0.05);
  transition: all 0.2s ease;
}

.quick-question-item:active {
  background-color: #e0e0e0;
  transform: scale(0.98);
}

.input-container {
  display: flex;
  align-items: center;
  background-color: #fff;
  border-radius: 40rpx;
  padding: 0 10rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.message-input {
  flex: 1;
  height: 80rpx;
  border-radius: 40rpx;
  background-color: #f5f5f5;
  padding: 0 24rpx;
  font-size: 28rpx;
  border: none;
}

.quick-questions-btn, .send-btn {
  width: 80rpx;
  height: 80rpx;
  margin-left: 10rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 40rpx;
  transition: all 0.2s ease;
}

.quick-questions-btn {
  background-color: #f0f0f0;
  font-size: 32rpx;
  color: #666;
}

.quick-questions-btn:active {
  background-color: #e0e0e0;
  transform: scale(0.95);
}

.send-btn {
  background-color: #e0e0e0;
  color: #999;
}

.send-btn.active {
  background-color: #4080FF;
  color: #fff;
}

.send-btn.active:active {
  transform: scale(0.95);
  background-color: #3070EE;
}
</style> 